<?php

namespace App\Services\Admin;



use App\Http\Models\Admin\File\File;
use Illuminate\Support\Facades\DB;

class FileManageService
{
     public function save($file){
          $file->type = str_replace(".","",$file->type);
          $file->save();
     }

     public function fileExtensions(){

          return DB::select('SELECT extension FROM files GROUP BY extension');

     }
     public function page($page,$length,$querys=null){

          $param = array();
          $start = $length*($page - 1);



         $prequery = DB::table('files')->orderBy('created_at',"desc")
              ->where(function  ($query) use ($querys,&$param) {
                   if($querys){
                        foreach($querys as $item){
                             $param[] = $item['p_name']. $item['type']. $item['value'];
                             $query->where($item['name'], $item['type'], $item['value']);
                        }
                   }
              });
          $total = $prequery->count();
          $datas = $prequery->skip($start)->take($length)->get();

          $total_page = ceil($total/$length);

          if($datas){
               foreach($datas as &$item) {
                    if (strlen($item->file_name) > 25) {
                         $item->file_name = mb_substr($item->file_name, 0, 10, 'utf-8')."***".mb_substr($item->file_name, mb_strlen($item->file_name,'utf-8')-10, 10, 'utf-8');
                    }
                    $item->tpl_file_name = $item->file_name;
                    $item->download_url = url($item->path);
               }
          }
          $pre_page =  $page>1?($page-1):$page;
          $next_page = $page<$total_page?($page+1):$page;


          return array(
               "total"=>$total,
               "currentpage"=>$page,
               "totalpage"=>$total_page,
               "prepage"=>implode("&",$param)."&page=".$pre_page,
               "nextpage"=>implode("&",$param)."&page=".$next_page,
               "datas"=>$datas
          );
     }
}
